package com.ruoyi.merchant.shop.service.impl;

import java.util.Date;
import java.util.List;

import com.ruoyi.common.core.constant.SecurityConstants;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.exception.ServiceException;
import com.ruoyi.merchant.area.domain.Area;
import com.ruoyi.merchant.area.mapper.AreaMapper;
import com.ruoyi.merchant.shopverification.domain.ShopVerification;
import com.ruoyi.merchant.shopverification.mapper.ShopVerificationMapper;
import com.ruoyi.merchant.shopverification.service.impl.ShopVerificationServiceImpl;
import com.ruoyi.system.api.RemoteUserService;
import com.ruoyi.system.api.domain.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ruoyi.merchant.shop.mapper.ShopMapper;
import com.ruoyi.merchant.shop.domain.Shop;
import com.ruoyi.merchant.shop.service.IShopService;
import com.ruoyi.merchant.shop.service.ILocationService;
import org.slf4j.LoggerFactory;

/**
 * 店铺信息Service业务层处理
 * 
 * @author zzr
 * @date 2025-09-14
 */
@Service
public class ShopServiceImpl implements IShopService {
    private static final org.slf4j.Logger logger = LoggerFactory.getLogger(ShopVerificationServiceImpl.class);

    @Autowired
    private ShopMapper shopMapper;

    @Autowired
    private AreaMapper areaMapper;


    @Autowired
    private ILocationService locationService;

    @Autowired
    private RemoteUserService remoteUserService;
    @Autowired
    private SmsServiceImpl smsServiceImpl;
    @Autowired
    private ShopVerificationMapper shopVerificationMapper;

    /**
     * 查询店铺信息
     *
     * @param id 店铺信息主键
     * @return 店铺信息
     */
    @Override
    public Shop selectShopById(Integer id) {
        return shopMapper.selectShopById(id);
    }

    /**
     * 查询店铺信息列表
     *
     * @param shop 店铺信息
     * @return 店铺信息
     */
    @Override
    public List<Shop> selectShopList(Shop shop) {
        return shopMapper.selectShopList(shop);
    }

    /**
     * 实现全查店铺信息（不分页）
     */
    @Override
    public List<Shop> selectAllShop(Shop shop)
    {
        // 调用Mapper全查方法，传递筛选条件
        return shopMapper.selectAllShop(shop);
    }

    /**
     * 新增店铺信息
     *
     * @param shop 店铺信息
     * @return 结果
     */
    @Override
    public Integer insertShop(Shop shop) {
        System.out.println("前端发送的信息:" + shop);
        /*业务逻辑*/
        shop.setRegTime(new Date());//默认注册时间是插入数据的时间

        // 根据地址，将地址转换为经纬度坐标返回给longitude和latitude
        // 暂时注释掉，因为腾讯地图API调用量达到上限
        /*
        if (StringUtils.isNotEmpty(shop.getAddress()) &&
                (StringUtils.isEmpty(shop.getLongitude()) || StringUtils.isEmpty(shop.getLatitude()))) {
            LocationResult locationResult = locationService.getLocationByAddress(shop.getAddress());
            if (locationResult.getStatus() == 0) {
                shop.setLongitude(locationResult.getLongitude());
                shop.setLatitude(locationResult.getLatitude());
                System.out.println("自动获取到经纬度: " + locationResult.getLongitude() + ", " + locationResult.getLatitude());
            } else {
                System.out.println("获取经纬度失败: " + locationResult.getMessage());
            }
        }
        */
        /*评分默认为0*/
        if (shop.getRate() == null) {
            shop.setRate(0);
        }


        // 从经营区域中截取省后面到市前面的部分
        String operatingArea = shop.getOperatingArea();
        String areatext = null;
        // 按“省”分割，得到["河南", "郑州市金水区"]
        String[] provinceSplit = operatingArea.split("省");
        if (provinceSplit.length > 1) {
            // 取分割后的第二部分“郑州市金水区”
            String cityAndDistrict = provinceSplit[1];
            // 按“市”分割，得到["郑州", "金水区"]
            String[] citySplit = cityAndDistrict.split("市");
            if (citySplit.length > 0) {
                // 取分割后的第一部分“郑州”
                areatext = citySplit[0];
            }
        }
        /*根据经营区域判断所属区域id
         * 如果没有查询到信息，就将该信息插入进入
         * 如果查询到信息，就返回id，作为area给shop
         * */
        Integer i1 = areaMapper.selectByArea(areatext);
        if (i1 == null) {
            Area area = new Area();
            area.setAreaName(areatext);
            areaMapper.insertArea(area);
            shop.setArea(areaMapper.selectByArea(areatext));
        } else {
            shop.setArea(i1);
        }

        shop.setStatus(0);//店铺经营状态默认为营业
        // 不设置auditStatus，让数据库使用默认值或NULL
        // shop.setAuditStatus(0);//店铺审核状态为待审核

        int i = shopMapper.insertShop(shop);
        return i > 0 ? shop.getId() : -1;//-1标识插入失败
    }

    /**
     * 修改店铺信息
     *
     * @param shop 店铺信息
     * @return 结果
     */
    @Override
    public int updateShop(Shop shop) {
        return shopMapper.updateShop(shop);
    }

    /**
     * 批量删除店铺信息
     *
     * @param ids 需要删除的店铺信息主键
     * @return 结果
     */
    @Override
    public int deleteShopByIds(Integer[] ids) {
        return shopMapper.deleteShopByIds(ids);
    }

    /**
     * 删除店铺信息信息
     *
     * @param id 店铺信息主键
     * @return 结果
     */
    @Override
    public int deleteShopById(Integer id) {
        return shopMapper.deleteShopById(id);
    }

    @Override
    public List<Shop> selectAll() {
        return shopMapper.selectAll();
    }

    /**
     * 根据传递过来的审核状态
     * 如果审核状态为1，就是审核通过，
     * 就调用系统的注册接口，为用户注册，并为用户授予角色[并通知用户商铺注册成功，并告诉用户访问的地址]
     * 如果审核状态为3，就是审核不通过，
     * 就不需要为用户注册[需要给用户发送短信，通知用户商铺审核失败]
     */

    //审核通过
    @Override
    public int auditStatusTrue(ShopVerification shopVerification) {
        /** 修改审核状态为1 审核通过*/
        shopMapper.auditStatusTrue(shopVerification.getMid());
        SysUser user = new SysUser();
        user.setPhonenumber(shopVerification.getMobile());
        user.setUserName(shopVerification.getMobile());
        user.setNickName(shopVerification.getMobile());
        user.setCreateTime(new java.util.Date());
        user.setRemark("商家");
        String mobile = shopVerification.getMobile();
        try {
            // 调用远程用户注册接口
            R<Boolean> result = remoteUserService.registerUserInfo(user, SecurityConstants.INNER);

            /** 发送信息通知用户注册成功*/
            smsServiceImpl.sendMsg(shopVerification.getMobile(), 0);

            if (result != null && result.getCode() == 200 && Boolean.TRUE.equals(result.getData())) {
                logger.info("商家用户注册成功，手机号: {}, 用户名: {}", shopVerification.getMobile(), user.getUserName());

                // 注册成功后，需要获取用户ID
                // 由于注册接口只返回Boolean，我们需要通过用户名查询用户ID
                R<com.ruoyi.system.api.model.LoginUser> userInfoResult = remoteUserService.getUserInfo(mobile, SecurityConstants.INNER);
                if (userInfoResult != null && userInfoResult.getCode() == 200 && userInfoResult.getData() != null) {
                    Long userId = userInfoResult.getData().getSysUser().getUserId();
                    logger.info("获取到用户ID: {}", userId);
                    return Math.toIntExact(userId);
                } else {
                    logger.error("获取用户信息失败，手机号: {}", mobile);
                    throw new ServiceException("获取用户信息失败");
                }
            } else {
                logger.error("商家用户注册失败，手机号: {}, 错误信息: {}", mobile, result != null ? result.getMsg() : "响应为空");
                throw new ServiceException("用户注册失败: " + (result != null ? result.getMsg() : "响应为空"));
            }

        } catch (Exception e) {
            logger.error("调用远程用户注册服务异常，手机号: {}", mobile, e);
            throw new ServiceException("调用用户注册服务异常: " + e.getMessage());
        }
    }

    //审核通过
    @Override
    public int auditStatusFalse(ShopVerification shopVerification) {
        /** 修改审核状态为3 审核不通过*/
        shopMapper.auditStatusFalse(shopVerification.getMid());
        /** 发送信息通知用户注册失败*/
        smsServiceImpl.sendMsg(shopVerification.getMobile(), 1);
        return 0;
    }

    @Override
    public Shop selectShopInfo(String mobile) {
        ShopVerification shopVerification = shopVerificationMapper.selectShopVerificationByMobile(mobile);
        return shopMapper.selectShopById(shopVerification.getMid());
    }


    /* *//**
     * 从经营区域中截取省后面到市前面的部分
     *
     * @param operatingArea 经营区域字符串，格式如："广东省深圳市南山区" 或 "北京市朝阳区"
     * @return 截取的区域部分，如果无法截取则返回null
     *//*
    private String extractAreaFromOperatingArea(String operatingArea) {
        if (StringUtils.isEmpty(operatingArea)) {
            return null;
        }

        try {
            // 定义省份后缀
            String[] provinceSuffixes = {"省", "市", "自治区", "特别行政区"};
            // 定义城市后缀
            String[] citySuffixes = {"市", "县", "区", "旗", "自治州", "地区"};

            String result = operatingArea;

            // 1. 先去掉省份部分
            for (String suffix : provinceSuffixes) {
                if (result.contains(suffix)) {
                    int index = result.indexOf(suffix);
                    if (index != -1) {
                        result = result.substring(index + suffix.length());
                        break;
                    }
                }
            }

            // 2. 再截取到市前面的部分
            for (String suffix : citySuffixes) {
                if (result.contains(suffix)) {
                    int index = result.indexOf(suffix);
                    if (index != -1) {
                        result = result.substring(0, index);
                        break;
                    }
                }
            }

            // 如果截取结果为空，返回null
            if (StringUtils.isEmpty(result)) {
                return null;
            }

            return result;

        } catch (Exception e) {
            System.out.println("截取经营区域失败: " + e.getMessage());
            return null;
        }
    }*/

}
